package org.black.phoneUtility.sms.schedule.app.fragment;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.schedule.database.dataModel.SmsSchedule;
import org.black.phoneUtility.sms.schedule.database.dataModel.SmsScheduleRecipient;
import org.black.phoneUtility.sms.schedule.provider.SmsScheduleContract;
import org.black.phoneUtility.sms.schedule.service.SmsScheduleService;

import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.OperationApplicationException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SmsScheduleAddEditFragment extends Fragment implements
		View.OnClickListener {
	public static final String TAG = SmsScheduleAddEditFragment.class.getName();

	private static final String LOG_TAG = SmsScheduleAddEditFragment.class
			.getName();
	public static final String ARGUMENTS_SMS_SCHEDULE_ID = "smsScheduleId";

	private SmsSchedule smsSchedule;
	private SmsScheduleService smsScheduleService;

	private class LoadSmsScheduleAsyncTas extends
			AsyncTask<Long, Void, SmsSchedule> {

		@Override
		protected SmsSchedule doInBackground(Long... params) {
			Long id = params[0];
			SmsSchedule result = null;
			if (smsSchedule == null) {
				result = smsScheduleService.read(id);
			} else {
				result = smsSchedule;
			}
			return result;
		}

		@Override
		protected void onPostExecute(SmsSchedule result) {
			super.onPostExecute(result);
			View view = getView();
			if (view != null) {
				smsSchedule = result;
				EditText subjectEditText = (EditText) view
						.findViewById(R.id.smsScheduleAddEditSubjectEditText);
				if (TextUtils.isEmpty(smsSchedule.getSubject()) == false) {
					subjectEditText.setText(smsSchedule.getSubject());
				}

				TextView smsScheduleAddEditRecipientsSummaryTextView = (TextView) view
						.findViewById(R.id.smsScheduleAddEditMessageSummaryTextView);
				if (TextUtils.isEmpty(smsSchedule.getMessage()) == false) {
					smsScheduleAddEditRecipientsSummaryTextView
							.setText(smsSchedule.getMessage());
				} else {
					smsScheduleAddEditRecipientsSummaryTextView
							.setText(getString(R.string.sms_schedule_add_edit_message_edit_text_hint));
				}
				TextView recipientsSummaryTextView = (TextView) view
						.findViewById(R.id.smsScheduleAddEditRecipientsSummaryTextView);
				if (smsSchedule.getSmsScheduleRecipients() != null
						&& smsSchedule.getSmsScheduleRecipients().size() > 0) {
					StringBuilder builder = new StringBuilder();
					boolean isFirst = true;
					for (SmsScheduleRecipient smsScheduleRecipient : smsSchedule
							.getSmsScheduleRecipients()) {
						if (isFirst == false) {
							builder.append(", ");
						} else {
							isFirst = !isFirst;
						}
						if (smsScheduleRecipient.getType() == SmsScheduleContract.SmsScheduleRecipients.TYPE_USER_INPUT) {
							builder.append(smsScheduleRecipient
									.getPhoneNumber());
						} else {
							builder.append(smsScheduleRecipient.getName()
									+ " ( "
									+ smsScheduleRecipient.getPhoneNumber()
									+ " )");
						}
					}
					recipientsSummaryTextView.setText(builder.toString());
				} else {
					recipientsSummaryTextView.setText(getString(R.string.none));
				}
				TextView dateSummaryTextView = (TextView) view
						.findViewById(R.id.smsScheduleAddEditDateSummaryTextView);
				if (smsSchedule.getScheduleDateTime() != null) {
					dateSummaryTextView.setText(DateFormat.getDateFormat(
							getActivity()).format(
							smsSchedule.getScheduleDateTime()));
				}
				if (smsSchedule.getScheduleDateTime() != null) {
					TextView timeSummaryTextView = (TextView) view
							.findViewById(R.id.smsScheduleAddEditTimeSummaryTextView);
					timeSummaryTextView.setText(DateFormat.getTimeFormat(
							getActivity()).format(
							smsSchedule.getScheduleDateTime()));
				}

				TextView repeatSummaryTextView = (TextView) view
						.findViewById(R.id.smsScheduleAddEditRepeatSummaryTextView);
				StringBuilder repeatSummary = new StringBuilder();

				if (smsSchedule.getRepeatType() == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_NONE) {
					repeatSummary
							.append(getString(R.string.sms_schedule_add_edit_repeat_no_repeat));
				} else {
					switch (smsSchedule.getRepeatType()) {
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_EVERY_MINUTE:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_minutes,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						break;
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_HOURLY:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_hours,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						break;
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_DAILY:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_daily,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						break;
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_WEEKLY:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_weekly,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						if (smsSchedule.isRepeatOnSunday() == false
								&& smsSchedule.isRepeatOnMonday() == false
								&& smsSchedule.isRepeatOnTuesday() == false
								&& smsSchedule.isRepeatOnWednesday() == false
								&& smsSchedule.isRepeatOnThursday() == false
								&& smsSchedule.isRepeatOnFriday() == false
								&& smsSchedule.isRepeatOnSaturday() == false) {
						} else {
							if (smsSchedule.isRepeatOnSunday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.sunday_abbreviation));
							}
							if (smsSchedule.isRepeatOnMonday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.monday_abbreviation));
							}
							if (smsSchedule.isRepeatOnTuesday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.tuesday_abbreviation));
							}
							if (smsSchedule.isRepeatOnWednesday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.wednesday_abbreviation));
							}
							if (smsSchedule.isRepeatOnThursday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.thursday_abbreviation));
							}
							if (smsSchedule.isRepeatOnFriday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.friday_abbreviation));
							}
							if (smsSchedule.isRepeatOnSaturday() == true) {
								repeatSummary.append(" "
										+ getString(R.string.comma));
								repeatSummary
										.append(getString(R.string.saturday_abbreviation));
							}

						}
						break;
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_MONTHLY:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_monthly,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						break;
					case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_YEARLY:
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_repeat_yearly,
								smsSchedule.getRepeatEvery(),
								smsSchedule.getRepeatEvery()));
						break;
					default:
						Log.e(LOG_TAG,
								"repeatType does not support. repeatType: "
										+ smsSchedule.getRepeatType());
						break;
					}

					switch (smsSchedule.getEndType()) {
					case SmsScheduleContract.SmsSchedules.END_TYPE_NEVER:
						repeatSummary.append(" " + getString(R.string.comma));
						repeatSummary
								.append(getString(R.string.sms_schedule_add_edit_end_never_ends));
						break;
					case SmsScheduleContract.SmsSchedules.END_TYPE_AFTER_TIMES:
						repeatSummary.append(" " + getString(R.string.comma));
						repeatSummary.append(getResources().getQuantityString(
								R.plurals.sms_schedule_add_edit_end_on_times,
								smsSchedule.getEndAfterTimes(),
								smsSchedule.getEndAfterTimes()));
						break;
					case SmsScheduleContract.SmsSchedules.END_TYPE_ON_SPECIFIC_DATETIME:
						repeatSummary.append(" " + getString(R.string.comma));
						repeatSummary
								.append(getString(R.string.sms_schedule_add_edit_end_ends_on)
										+ " "
										+ DateFormat
												.getDateFormat(getActivity())
												.format(smsSchedule
														.getEndOnSpecificDateTime()));
						break;
					default:
						Log.e(LOG_TAG, "endType does not support: endType: "
								+ smsSchedule.getEndType());
						break;
					}

				}
				repeatSummaryTextView.setText(repeatSummary.toString());
			}

			view.findViewById(R.id.smsScheduleAddEditContentScrollViewayout)
					.setVisibility(View.VISIBLE);
			view.findViewById(R.id.smsScheduleAddEditLoadingPanelLinearLayout)
					.setVisibility(View.GONE);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			View view = getView();
			view.findViewById(R.id.smsScheduleAddEditContentScrollViewayout)
					.setVisibility(View.GONE);
			view.findViewById(R.id.smsScheduleAddEditLoadingPanelLinearLayout)
					.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// To hook action bar menu
		setHasOptionsMenu(true);

		this.smsScheduleService = new SmsScheduleService(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = getView();
		if (view == null) {
			view = inflater.inflate(R.layout.sms_schedule_add_edit, container,
					false);
			RelativeLayout addEditMessageSettingRelativeLayout = (RelativeLayout) view
					.findViewById(R.id.smsScheduleAddEditMessageSettingRelativeLayout);
			addEditMessageSettingRelativeLayout.setOnClickListener(this);

			RelativeLayout recipientsRelativeLayout = (RelativeLayout) view
					.findViewById(R.id.smsScheduleAddEditRecipientsSettingRelativeLayout);
			recipientsRelativeLayout.setOnClickListener(this);

			RelativeLayout dateRelativeLayout = (RelativeLayout) view
					.findViewById(R.id.smsScheduleAddEditdDateRelativeLayout);
			dateRelativeLayout.setOnClickListener(this);

			RelativeLayout timeRelativeLayout = (RelativeLayout) view
					.findViewById(R.id.smsScheduleAddEditdTimeRelativeLayout);
			timeRelativeLayout.setOnClickListener(this);

			RelativeLayout repeatRelativeLayout = (RelativeLayout) view
					.findViewById(R.id.smsScheduleAddEditRepeatRelativeLayout);
			repeatRelativeLayout.setOnClickListener(this);
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().setTitle(
				getString(R.string.sms_schedule_add_edit_setting));

		getActivity().getActionBar().setLogo(R.drawable.ic_action_accept);
		getActivity().getActionBar().setTitle(getString(R.string.done));
		getActivity().getActionBar().setDisplayOptions(
				ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_TITLE
						| ActionBar.DISPLAY_SHOW_HOME);
		long id = getArguments().getLong(ARGUMENTS_SMS_SCHEDULE_ID);
		new LoadSmsScheduleAsyncTas().execute(id);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.sms_schedule_add_edit_actions, menu);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.smsSchedule = null;
		this.smsScheduleService = null;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// TODO: update do done
		case android.R.id.home:
			getActivity().onBackPressed();
			return true;
		case R.id.menu_sms_schedule_add_edit_discard:
			getActivity().finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void handleSmsScheduleDateTimeDatePickerDialogPositiveClick(
			int year, int monthOfYear, int dayOfMonth) {
		if (smsSchedule != null) {
			if (smsSchedule.getScheduleDateTime() == null) {
				smsSchedule.setScheduleDateTime(new Date());
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(smsSchedule.getScheduleDateTime());
			calendar.set(Calendar.MILLISECOND, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

			this.smsSchedule.setScheduleDateTime(calendar.getTime());
			TextView dateSummaryTextView = (TextView) getView().findViewById(
					R.id.smsScheduleAddEditDateSummaryTextView);
			if (smsSchedule.getScheduleDateTime() != null) {
				dateSummaryTextView.setText(DateFormat.getDateFormat(
						getActivity())
						.format(smsSchedule.getScheduleDateTime()));
			}
		}

	}

	public void handleSmsScheduleDateTimeTimePickerDialogPositiveClick(
			int hourOfDay, int minute) {
		if (smsSchedule != null) {
			if (smsSchedule.getScheduleDateTime() == null) {
				smsSchedule.setScheduleDateTime(new Date());
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(smsSchedule.getScheduleDateTime());
			calendar.set(Calendar.MILLISECOND, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calendar.set(Calendar.MINUTE, minute);

			this.smsSchedule.setScheduleDateTime(calendar.getTime());
			TextView timeSummaryTextView = (TextView) getView().findViewById(
					R.id.smsScheduleAddEditTimeSummaryTextView);
			if (smsSchedule.getScheduleDateTime() != null) {
				timeSummaryTextView.setText(DateFormat.getTimeFormat(
						getActivity())
						.format(smsSchedule.getScheduleDateTime()));
			}
		}

	}

	public void insertOrUpdate() {
		try {
			this.smsSchedule.setActivated(false);
			this.smsScheduleService.insertOrUpdate(smsSchedule);
			if (smsSchedule.getId() != null) {
				Toast.makeText(
						getActivity(),
						getString(
								R.string.sms_schedule_add_edit_update_settings,
								this.smsSchedule.getSubject().replace("\r\n",
										"")), Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(
						getActivity(),
						getString(
								R.string.sms_schedule_add_edit_create_new_settings,
								this.smsSchedule.getSubject().replace("\r\n",
										"")), Toast.LENGTH_SHORT).show();
			}
		} catch (RemoteException e) {
			Log.e(LOG_TAG, "RemoteException", e);
		} catch (OperationApplicationException e) {
			Log.e(LOG_TAG, "OperationApplicationException", e);
		}
	}

	public void handleEditAddSmsMessage(String newMessage) {
		if (this.smsSchedule != null) {
			this.smsSchedule.setMessage(newMessage);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.smsScheduleAddEditMessageSettingRelativeLayout: {
			Fragment newFragment = new SmsScheduleAddEditMessageFragment();
			FragmentTransaction transaction = getActivity()
					.getFragmentManager().beginTransaction();

			transaction.setCustomAnimations(
					R.animator.right_slide_enter_object_animator,
					R.animator.right_slide_exist_object_animator,
					R.animator.left_slide_enter_object_animator,
					R.animator.left_slide_exist_object_animator);
			Bundle bundle = new Bundle();
			bundle.putSerializable(
					SmsScheduleAddEditMessageFragment.ARGUMENTS_SMS_SCHEDULE,
					smsSchedule);
			newFragment.setArguments(bundle);
			transaction.replace(R.id.sms_schedule_add_edit_main_content_frame,
					newFragment, SmsScheduleAddEditMessageFragment.TAG);
			transaction.addToBackStack(null);

			transaction.commit();

			break;
		}
		case R.id.smsScheduleAddEditRecipientsSettingRelativeLayout: {
			Fragment newFragment = new SmsScheduleRecipientsListFragment();
			FragmentTransaction transaction = getActivity()
					.getFragmentManager().beginTransaction();

			transaction.setCustomAnimations(
					R.animator.right_slide_enter_object_animator,
					R.animator.right_slide_exist_object_animator,
					R.animator.left_slide_enter_object_animator,
					R.animator.left_slide_exist_object_animator);
			Bundle bundle = new Bundle();
			bundle.putSerializable(
					SmsScheduleRecipientsListFragment.ARGUMENTS_SMS_SCHEDULE_RECIPIENTS_LIST,
					(Serializable) smsSchedule.getSmsScheduleRecipients());
			newFragment.setArguments(bundle);
			transaction.replace(R.id.sms_schedule_add_edit_main_content_frame,
					newFragment);
			transaction.addToBackStack(null);

			transaction.commit();
			break;
		}
		case R.id.smsScheduleAddEditdDateRelativeLayout: {
			SmsScheduleDateTimeDatePickerDialogFragment smsScheduleDateTimeDatePickerDialogFragment = new SmsScheduleDateTimeDatePickerDialogFragment();
			Bundle bundle = new Bundle();
			Calendar calendar = Calendar.getInstance();
			if (smsSchedule.getScheduleDateTime() != null) {
				calendar.setTime(smsSchedule.getScheduleDateTime());
			}

			bundle.putInt(
					SmsScheduleDateTimeDatePickerDialogFragment.ARGUMENTS_YEAR,
					calendar.get(Calendar.YEAR));
			bundle.putInt(
					SmsScheduleDateTimeDatePickerDialogFragment.ARGUMENTS_MONTH,
					calendar.get(Calendar.MONTH));
			bundle.putInt(
					SmsScheduleDateTimeDatePickerDialogFragment.ARGUMENTS_DATE,
					calendar.get(Calendar.DAY_OF_MONTH));
			smsScheduleDateTimeDatePickerDialogFragment.setArguments(bundle);
			smsScheduleDateTimeDatePickerDialogFragment.show(
					getFragmentManager(),
					SmsScheduleDateTimeDatePickerDialogFragment.TAG);
			break;
		}
		case R.id.smsScheduleAddEditdTimeRelativeLayout: {
			SmsScheduleDateTimeTimePickerDialogFragment smsScheduleDateTimeTimePickerDialogFragment = new SmsScheduleDateTimeTimePickerDialogFragment();
			Bundle bundle = new Bundle();
			Calendar calendar = Calendar.getInstance();
			if (smsSchedule.getScheduleDateTime() != null) {
				calendar.setTime(smsSchedule.getScheduleDateTime());
			}

			bundle.putInt(
					SmsScheduleDateTimeTimePickerDialogFragment.ARGUMENTS_HOUR_OF_DAY,
					calendar.get(Calendar.HOUR_OF_DAY));
			bundle.putInt(
					SmsScheduleDateTimeTimePickerDialogFragment.ARGUMENTS_MINUTE,
					calendar.get(Calendar.MINUTE));
			smsScheduleDateTimeTimePickerDialogFragment.setArguments(bundle);
			smsScheduleDateTimeTimePickerDialogFragment.show(
					getFragmentManager(),
					SmsScheduleDateTimeTimePickerDialogFragment.TAG);
			break;
		}
		case R.id.smsScheduleAddEditRepeatRelativeLayout: {
			Fragment newFragment = new SmsScheduleRepeatFragment();
			FragmentTransaction transaction = getActivity()
					.getFragmentManager().beginTransaction();

			transaction.setCustomAnimations(
					R.animator.right_slide_enter_object_animator,
					R.animator.right_slide_exist_object_animator,
					R.animator.left_slide_enter_object_animator,
					R.animator.left_slide_exist_object_animator);
			Bundle bundle = new Bundle();
			bundle.putSerializable(
					SmsScheduleRepeatFragment.ARGUMENTS_SMS_SCHEDULE,
					(Serializable) smsSchedule);
			newFragment.setArguments(bundle);
			transaction.replace(R.id.sms_schedule_add_edit_main_content_frame,
					newFragment);
			transaction.addToBackStack(null);

			transaction.commit();
			break;
		}
		default:
			break;
		}

	}
}
